<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form action="http://www.biwuit.cn/spboot/userLoginPostRequest" id="form1">
        用户名：<input type="text" name="username"><br>
        密码：<input type="password" name="password"><br>
        <input type="submit" value="提交">
    </form>

    <script>
        /* 
            问题：如果表单的输入项很多的话，需要手动的获取表单输入项的值，比较繁琐
            有没有简单的方式？
            可以使用FormDate()
         */
        const request = new XMLHttpRequest();
        const form1Obj = document.querySelector("#form1")
        const inputs = document.querySelectorAll("input")

        form1Obj.addEventListener("submit", function (e) {
            //参数表单对象作为参数,自动完成参数的收集
            const formDataObj = new FormData(form1Obj)

            //阻止表单的提交
            e.preventDefault();

            //通过Ajax提交
            request.open("POST", "http://www.biwuit.cn/spboot/formDataRequest")

            //头部信息      如果数据格式是FormData，不需要头部信息
            // request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            //获取数据
            // const usernameValue = inputs[0].value;
            // const passwordValue = inputs[1].value;
            // const args = "username="+usernameValue+"&"+"password="+passwordValue;

            //使用FormDate获取参数
            console.log(formDataObj.get("username"))
            console.log(formDataObj.get("password"))

            request.send(formDataObj)

            // request.send(args)
            request.onreadystatechange = function () {
                if (request.readyState == 4 && request.status == 200) {
                    console.log(request.responseText)
                }
                
            }

        })
    </script>
</body>

</html>